package com.shop.cereshop.app.controller.kuaidi100;

import com.alibaba.fastjson.JSON;
import com.kuaidi100.sdk.request.PrintReq;
import com.shop.cereshop.app.service.bsamecity.BsamecityOrderService;
import com.shop.cereshop.app.service.express.KuaiDi100Service;
import com.shop.cereshop.commons.domain.kuaidi.kd100.order.resp.Kd100BaseResp;
import com.shop.cereshop.commons.domain.kuaidi.kd100.order.resp.PlaceAnOrderCallbackParam;
import com.shop.cereshop.commons.domain.kuaidi.kd100.order.resp.callBack.BasameCityOrderCallbackParam;
import com.shop.cereshop.commons.domain.kuaidi.kd100.order.resp.callBack.CallBackBaseModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("kd100")
@Slf4j
@Api(value = "快递100接口", tags = "快递100接口")
public class Kd100Controller {
    @Resource
    private KuaiDi100Service kuaiDi100Service;
    @Resource
    private BsamecityOrderService bsamecityOrderService;

    /**
     * 下单回调接口
     * 订单有状态变更是会触发回调，回调后如果没有得到合作方正确返回，会重复回调多2次，即最多回调3次。间隔30分钟。
     * 提供统一格式的HTTP POST,并返回统一格式JSON数据。
     * 请求报头：Content-Type=application/x-www-form-urlencoded;charset=UTF-8
     */
    @PostMapping("placeAnOrderCallback")
    @ApiOperation(value = "快递100下单回调接口", notes = "处理快递100下单状态变更回调")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "kuaidicom", value = "快递公司编码", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "kuaidinum", value = "快递单号", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "status", value = "状态码", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "message", value = "状态描述", required = true, dataType = "string", paramType = "form")
    })
    public Kd100BaseResp<Object> placeAnOrderCallback(PlaceAnOrderCallbackParam param) {
        log.info("kd100下单回调参数：{}", param);
        return Kd100BaseResp.builder()
                .result(true)
                .returnCode("200")
                .message("成功收到消息" + param.getKuaidinum())
                .build();
    }

    /**
     * 同城配送订单状态回调接口
     */
    @PostMapping("bsamecityOrderCallback")
    @ApiOperation(value = "同城配送订单状态回调接口", notes = "处理同城配送订单状态变更回调")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", value = "任务ID", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "sign", value = "签名", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "param", value = "回调参数（JSON字符串）", required = true, dataType = "string", paramType = "form")
    })
    public Kd100BaseResp<Object> bsamecityOrderCallback(HttpServletRequest request) {
        try {
            log.info("同城配送订单状态回调参数：{}", request.getParameterMap());
            // 读取表单参数
            Map<String, String[]> parameterMap = request.getParameterMap();

            // 构造回调基础模型
            CallBackBaseModel<BasameCityOrderCallbackParam> callBackModel = new CallBackBaseModel<>();

            // 设置基础字段
            if (parameterMap.containsKey("taskId")) {
                callBackModel.setTaskId(parameterMap.get("taskId")[0]);
            }
            if (parameterMap.containsKey("sign")) {
                callBackModel.setSign(parameterMap.get("sign")[0]);
            }

            // 处理param参数（JSON字符串）
            if (parameterMap.containsKey("param")) {
                String paramJson = parameterMap.get("param")[0];
                // 将JSON字符串转换为BasameCityOrderCallbackParam对象
                BasameCityOrderCallbackParam callbackParam = JSON.parseObject(paramJson, BasameCityOrderCallbackParam.class);
//                callBackModel.setParam(callbackParam);
                bsamecityOrderService.saveOrderStatus(callBackModel.getTaskId(), callbackParam);
//                log.info("同城配送订单状态回调参数：{}", callBackModel);
//                System.out.println(callbackParam.toString());
            }

            return Kd100BaseResp.builder()
                    .result(true)
                    .returnCode("200")
                    .message("成功收到消息")
                    .build();
        } catch (Exception e) {
            log.error("处理同城配送订单状态回调异常：", e);
            return Kd100BaseResp.builder()
                    .result(false)
                    .returnCode("500")
                    .message("处理回调异常：" + e.getMessage())
                    .build();
        }
    }
}
